package in.falkeninc.umt_v0_9_8_1;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import com.actionbarsherlock.app.SherlockFragmentActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;

import android.widget.TextView;

public class AlarmInfoAdapter extends ArrayAdapter<AlarmInfo> {

	Context context; 
    int layoutResourceId;    
    ArrayList<AlarmInfo> data = null;
    
    private int selectedPos = -1;		// init value for not-selected
    private String selectedId = null;	// init value for not-selected
    
	public AlarmInfoAdapter(Context context, int layoutResourceId, ArrayList<AlarmInfo> in_data)
	{
		super(context, layoutResourceId, in_data);
		
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = in_data;	

        Log.d("arraydump: ", String.valueOf(in_data.size()));
	}

	@SuppressLint("SimpleDateFormat")
	@Override
    public View getView(int position, View convertView, ViewGroup parent)
	{	
        View row = convertView;
        
        AlarmHolder holder = null;
        
        if(row == null)
        {
        	LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        	
            row = inflater.inflate(layoutResourceId, parent, false);
            
            holder = new AlarmHolder();

            holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
            holder.id = (TextView)row.findViewById(R.id.myid);
            holder.txtName = (TextView)row.findViewById(R.id.txtName);
            holder.txtDesc = (TextView)row.findViewById(R.id.txtDesc);
            holder.txtWhen = (TextView)row.findViewById(R.id.txtWhen);
            holder.txtEnabled = (TextView)row.findViewById(R.id.txtEnabled);
            holder.txtSnooze = (TextView)row.findViewById(R.id.txtSnooze);
            holder.txtRepeats = (TextView)row.findViewById(R.id.txtRepeats);
            
            holder.imgIconMon= (ImageView)row.findViewById(R.id.iconMon);
            holder.imgIconTue= (ImageView)row.findViewById(R.id.iconTue);
            holder.imgIconWed= (ImageView)row.findViewById(R.id.iconWed);
            holder.imgIconThu= (ImageView)row.findViewById(R.id.iconThu);
            holder.imgIconFri= (ImageView)row.findViewById(R.id.iconFri);
            holder.imgIconSat= (ImageView)row.findViewById(R.id.iconSat);
            holder.imgIconSun= (ImageView)row.findViewById(R.id.iconSun);
                        
            row.setTag(holder);
            
        } else {
        	
            holder = (AlarmHolder)row.getTag();
            
        }
        
        AlarmInfo alarm = data.get(position);

        holder.imgIcon.setImageResource(R.drawable.appicon);

        holder.imgIconMon.setImageResource(R.drawable.icon_monday16);
        holder.imgIconTue.setImageResource(R.drawable.icon_tuesday16);
        holder.imgIconWed.setImageResource(R.drawable.icon_wednesday16);
        holder.imgIconThu.setImageResource(R.drawable.icon_thursday16);
        holder.imgIconFri.setImageResource(R.drawable.icon_friday16);
        holder.imgIconSat.setImageResource(R.drawable.icon_saturday16);
        holder.imgIconSun.setImageResource(R.drawable.icon_sunday16);

        holder.id.setText((String.valueOf(alarm.getID())));
        holder.txtDesc.setText(alarm.getDescription());
        
        this.setSelectedPosition(position);

        /*        holder.holdll.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                    TextView t = (TextView)v.findViewById(R.id.myid);
                    setSelectedId(t.getText().toString());
                    return true;
            }
        });*/
 
        long curMillis = alarm.getAlarmtime();
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
		String dateFormatted = formatter.format(curMillis);
		holder.txtWhen.setText(dateFormatted);        
        holder.txtName.setText(alarm.getName()); 

        holder.txtRepeats.setText(String.valueOf(alarm.getRepeats())); 
        holder.txtSnooze.setText(alarm.getSnooze() == 1 ? "Yes" : "No"); 
        holder.txtEnabled.setText(alarm.getEnabled() == 1 ? "Yes" : "No"); 
        
        parse_daycode(alarm);
        
        return row;
    }

	public void setSelectedPosition(int pos){
		selectedPos = pos;
		// inform the view of this change
		notifyDataSetChanged();
	}

	public int getSelectedPosition(){
		return selectedPos;
	}

	public void setSelectedId(String string){
		selectedId = string;
		// inform the view of this change
		notifyDataSetChanged();
	}

	public String getSelectedId(){
		return selectedId;
	}
	
    static class AlarmHolder
    {
    	ImageView imgIcon;
    	TextView id;
    	
        TextView txtName;
        TextView txtDesc;
        TextView txtWhen;
        TextView txtEnabled;
        TextView txtSnooze;
        TextView txtRepeats;
        
        ImageView imgIconMon;
        ImageView imgIconTue;
        ImageView imgIconWed;
        ImageView imgIconThu;
        ImageView imgIconFri;
        ImageView imgIconSat;
        ImageView imgIconSun;
    }

	private void parse_daycode(AlarmInfo ai)
	{	
	    // *** ENABLE/DISABLE DAYS OF WEEK
		String daycode = ai.getDaycode();							// Check if alarm is supposed to run today
		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(Calendar.MONDAY);

		// Decode daycode into toggle buttons modes
		Log.d("PopulateDB:", "Daycode: " + daycode);

		// Now generate one or two strings of number, parsed out of the daycode from the database.
		// These numbers will then be iterated over to set the daycode in the TitlesFragment list
		
		String sd = "", sx = "";

		if (daycode.contains("d") && daycode.contains("x")) {
	
			// We have both, investigate further
			int i	= daycode.indexOf("d");						// We have a "d", find it's index 
			int j	= daycode.indexOf("x");						// We have an "x" too, find it's index
			
			if (j == (i + 1)) {
				// The x is right next to the d
				// So 'daily excluding the following:
				if (daycode.length() >= 3) {
					// We have a d, an x right next to it an length is 3 or more
					// So these days are excluded
		    		int k = daycode.length();
		    		// dx1234
		    		// __
		    		//  2
		    		// ______
		    		//   l=6
		    		//  6-2=4 = ok
		    		sx	= daycode.substring(j + 2, k - 2);				// s is now the enables days		
	        
		    		if (!sx.contains("1")) sd += "1";
		    		if (!sx.contains("2")) sd += "2";
		    		if (!sx.contains("3")) sd += "3";
		    		if (!sx.contains("4")) sd += "4";
		    		if (!sx.contains("5")) sd += "5";
		    		if (!sx.contains("6")) sd += "6";
		    		if (!sx.contains("7")) sd += "7";
		    		
		    		sd_helper(sd);
	        		sx_helper(sx);
		        	Log.d("Populate from DB 'dx' found: ", "x directly right of d");
		        	Log.d("Populate from DB x days = ", sx);
				}
	
			} else {
				
				// We have both and they are not next to each other.
				// So d and x has numbers after them,
				// Assume d is first!
				
	    		int k = daycode.length();
	    		sd	= daycode.substring(i + 1, j);				// s is now the enables days
	    		sx	= daycode.substring(j + 1, k);				// s is now the enables days
	    		sd_helper(sd);
	    		sx_helper(sx);
	    		
	        	Log.d("Populate from DB 'dx' found: ", "x not directly right of d");
	        	Log.d("Populate from DB d days = ", sd);
	        	Log.d("Populate from DB x days = ", sx);
				
			}
	
		} else if (daycode.contains("d") && !daycode.contains("x") && daycode.length() == 1) {
	
			// Only d
			int i 	=	daycode.indexOf("d");							// We have a "d", find it's index 
			int k	= 	daycode.length();
			sd		= 	"1234567";										// s is now the enables days
			sx		=	"";	 
	
			sd_helper(sd);
			
			Log.d("PopulateDB:", "'d' found: " + sd);
	
		} else if (!daycode.contains("d") && daycode.contains("x") && daycode.length() == 1) {
	
			// Only x, this is the default
			int j	= 	daycode.indexOf("x");							// We have an "x" too, find it's index
			int k	= 	daycode.length();
	    	sx 		= 	"1234567";
			sd		=	"";	 
	
			sx_helper(sx);
			
	    	Log.d("PopulateDB:", "'x' found: " + sx);
	
		} else if (!daycode.contains("d") && !daycode.contains("x")) {
			
	    	sx 	= 	"1234567";
			sd	=	"";	 
	
			sx_helper(sx);
			
	    	Log.d("PopulateDB:", "None of d or x found!! ");
	    	Log.d("PopulateDB:", "Assuming x: " + sx);
		}
	
		Log.d("PopulateDB:", "Finally, sd and sx was:");
		Log.d("PopulateDB:", sd + ", " + sx);
	}

	public void sx_helper(String sx)
	{
		ImageView img;
		SherlockFragmentActivity sfa =  (SherlockFragmentActivity) this.context;
		
		if(sx.contains("1")) {
			img = (ImageView)sfa.findViewById(R.id.iconMon);
			if (img == null) return;
			img.setAlpha(128);
		}
		if(sx.contains("2")) {
			img = (ImageView)sfa.findViewById(R.id.iconTue);
			img.setEnabled(false);
		}
		if(sx.contains("3")) {
			img = (ImageView)sfa.findViewById(R.id.iconWed);
			img.setEnabled(false);
		}
		if(sx.contains("4")) {
			img = (ImageView)sfa.findViewById(R.id.iconThu);
			img.setEnabled(false);
		}
		if(sx.contains("5")) {
			img = (ImageView)sfa.findViewById(R.id.iconFri);
			img.setEnabled(false);
		}
		if(sx.contains("6")) {
			img = (ImageView)sfa.findViewById(R.id.iconSat);
			img.setEnabled(false);
		}
		if(sx.contains("7")) {
			img = (ImageView)sfa.findViewById(R.id.iconSun);
			img.setEnabled(false);
		}
		
	}

	public void sd_helper(String sd)
	{
		ImageView img;
		SherlockFragmentActivity sfa =  (SherlockFragmentActivity) this.context;
		
		if(sd.contains("1")) {
			img = (ImageView)sfa.findViewById(R.id.iconMon);
			if (img == null) return;
			img.setAlpha(128);
		}
		if(sd.contains("2")) {
			img = (ImageView)sfa.findViewById(R.id.iconTue);
			img.setEnabled(true);
		}
		if(sd.contains("3")) {
			img = (ImageView)sfa.findViewById(R.id.iconWed);
			img.setEnabled(true);
		}
		if(sd.contains("4")) {
			img = (ImageView)sfa.findViewById(R.id.iconThu);
			img.setEnabled(true);
		}
		if(sd.contains("5")) {
			img = (ImageView)sfa.findViewById(R.id.iconFri);
			img.setEnabled(true);
		}
		if(sd.contains("6")) {
			img = (ImageView)sfa.findViewById(R.id.iconSat);
			img.setEnabled(true);
		}
		if(sd.contains("7")) {
			img = (ImageView)sfa.findViewById(R.id.iconSun);
			img.setEnabled(true);
		}
		
	}

	
}
